package com.wonderful.map.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.CornerPathEffect
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.wonderful.image.utils.PointUtil
import com.wonderful.map.R
import com.wonderful.map.bean.GridPositionBean

/**
 * Desc: 特征路径 View
 * @Author: wonderful
 * @Time: 2023/5/30 14:57
 */
class FeaturePathView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : View(context, attrs, defStyleAttr, defStyleRes) {

    private val mPathPaint = Paint()                            // 路径画笔
    private val mPathPoints = mutableListOf<GridPositionBean>() // 路径点
    private val mCornerEffect = CornerPathEffect(2f)     // 转弯圆角

    private val mTranslate: PointF = PointF()
    private var mScale: Float = 1f

    init {
        mPathPaint.apply {
            isAntiAlias = true
            style = Paint.Style.STROKE
            color = ContextCompat.getColor(context, R.color.color_feature_path)
            strokeWidth = 2f
            pathEffect = mCornerEffect
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        drawPath(canvas)
    }

    /**
     * 绘制路径
     */
    private fun drawPath(canvas: Canvas?) {
        for (i in 0 until mPathPoints.size - 1) {
            val p1 = mPathPoints[i]
            val p2 = mPathPoints[i + 1]
            val pointF = PointUtil.sourceToViewCoordinate(p1.x, p1.y, mTranslate, mScale)
            val nextPointF = PointUtil.sourceToViewCoordinate(p2.x, p2.y, mTranslate, mScale)
            canvas?.drawLine(pointF.x, pointF.y, nextPointF.x, nextPointF.y, mPathPaint)
        }
    }

    /**
     * 设置路径点
     */
    fun setPathPoints(
        points: List<GridPositionBean>,
        vTranslate: PointF,
        scale: Float,
        mapHeight: Int
    ) {
        mPathPoints.clear()
        for (point in points) {
            mPathPoints.add(GridPositionBean(point.x, point.y))
        }
        refreshView(vTranslate, scale)
    }

    /**
     * 刷新
     */
    fun refreshView(vTranslate: PointF, scale: Float) {
        mTranslate.set(vTranslate)
        mScale = scale
        invalidate()
    }

    /**
     * 清空数据
     */
    fun clear() {
        mPathPoints.clear()
        invalidate()
    }
}